package com.joysuch.wwyt.util;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.UUID;


@Component
@Slf4j
public class PrintExportUtil {

    @Value("${wwyt.print.template.word.path}")
    private String templatePath;

    @Value("${wwyt.upload.unzip.tempdir}")
    private String pdfTemplatePath;

    @Autowired
    private Configuration configuration;


    public byte[] exportWord(String templateWordName, Map<String, Object> dataMap) throws Exception {
        ClassPathResource resource = new ClassPathResource("templates"+File.separator+"font"+File.separator+"workSafetyCertRiskEvalTemp.docx");
        XWPFDocument document = WordExportUtil.exportWord07(resource.getPath(), dataMap);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        document.write(bos);
        return bos.toByteArray();
    }

    public File generatePDF(Map<String, Object> dataMap, String fileName) throws Exception {
        log.info("---------------------------------" + templatePath);

        if (!new File(templatePath + "//pdf").exists()) {
            new File(templatePath + "//pdf").mkdirs();
        }
        if (!new File(templatePath + "//html").exists()) {
            new File(templatePath + "//html").mkdirs();
        }
        String name = UUID.randomUUID().toString();
        String htmlName = name + ".html";
        String htmlUrl = templatePath + File.separator + "html" + File.separator + htmlName;
        String pdfName = name + ".pdf";
        String pdfUrl = templatePath + File.separator + "pdf" + File.separator + pdfName;
        createHtml(dataMap, fileName, htmlUrl);
        return htmlConvertPDF(htmlUrl, pdfUrl);
    }

    public File generateNewPDF(Map<String, Object> dataMap, String fileName,String newFileName) throws Exception {
        log.info("---------------------------------" + pdfTemplatePath);

        if (!new File(pdfTemplatePath + "//pdf").exists()) {
            new File(pdfTemplatePath + "//pdf").mkdirs();
        }
        if (!new File(pdfTemplatePath + "//html").exists()) {
            new File(pdfTemplatePath + "//html").mkdirs();
        }
        String htmlName = newFileName + ".html";
        String htmlUrl = pdfTemplatePath + File.separator + "html" + File.separator + htmlName;
        String pdfName = newFileName + ".pdf";
        String pdfUrl = pdfTemplatePath + File.separator + "pdf" + File.separator + pdfName;
        createHtml(dataMap, fileName, htmlUrl);
        return htmlConvertPDF(htmlUrl, pdfUrl);
    }

    private File html2pdf(String htmlFile, String pdfFile) throws Exception {
        //本地路径
        //	String url = new File(htmlFile).toURI().toURL().toString();
        //服务器路径
        String url = htmlFile;
        // step 2
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(new File(url));
        // step 3 解决中文支持
        ITextFontResolver fontResolver = renderer.getFontResolver();
        //fontResolver.addFont("F:/test//font/SimSun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        ClassPathResource resource = new ClassPathResource("templates/font/simsun.ttc");
        //ClassLoader loader = Thread.currentThread().getContextClassLoader();
        fontResolver.addFont(resource.getPath(),
                BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        FileOutputStream out = new FileOutputStream(pdfFile);
        renderer.layout();
        renderer.createPDF(out);
        out.close();
        System.out.println("create pdf done!!");
        return new File(pdfFile);
    }

    private void createHtml(Map<String, Object> map, String fileName, String desPath) throws Exception {
        Template template = configuration.getTemplate(fileName + ".ftl"); // freeMarker template
        File outfile = new File(desPath);
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "utf-8"));
        template.process(map, out);
        out.flush();
    }

    private File htmlConvertPDF(String htmlFile, String pdfFile) {
        // step 1
        Document document = new Document();
        try {
            // step 2
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            // step 3
            document.open();
            // step 4
            //XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, doc, input, null,charset,new FontProviderUtil());
           /* XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new FileInputStream(htmlFile), Charset.forName("UTF-8"));*/
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new FileInputStream(htmlFile),null, Charset.forName("UTF-8"),new FontProviderUtil());
            // step 5
            document.close();
        } catch (Exception e) {
            log.error("Html 转成PDF 报错", e);
            if (document != null) {
                document.close();
            }
        }
        return new File(pdfFile);
    }

}
